<template>
  <div class="fuchuang" ref="draggableBtn" @mousedown="startDrag" @touchstart="startDrag" :style="buttonStyle">
    <img class="fuchuang-img" src="/img/peilian.png" alt="" />
  </div>
  <div class="header">
    <div class="menuMedia" v-if="windowWidth < 768" @click="handleChangeMenu">
      <span></span>
      <span></span>
      <span></span>
    </div>
    <div class="kuandu">
      <div class="header-left" v-if="windowWidth > 768">
        <img  class="header-logo" :src="logoUrl" alt="logo" />
        <div class="header-menu">
          <div v-for="item in menuItems" :key="item.index"
            :class="[currentIndex === item.index ? 'menu-item-active' : 'menu-item']"
            @click="clickmenuItem(item.index, item.url)">
            <img class="menu-icon" :src="currentIndex === item.index ? item.icon : item.imgs" alt="" />
            <div class="daohang">{{ item.text }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="rigrt">
      <a-space direction="vertical" :size="16" style="display: block">
        <a-row class="grid-demo">
          <a-col :lg="7" :sm="4">
            <div class="xueke">当前学科：</div>
          </a-col>
          <a-col :lg="7" :sm="10">
            <div>
              <a-space direction="vertical" size="large">
                <a-select v-model="formdata.subjectId" class="selectname" placeholder="请选择学科"
                  @change="searchButtonClick">
                  <a-option v-for="(item, index) in myObject.gradeList" :key="index" :value="item.SubjectID"
                    :label="item.SubjectName">{{ item.SubjectName }}</a-option>
                </a-select>
              </a-space>
            </div>
          </a-col>
          <a-col :span="2">
            <div style="margin-top: 3px"></div>
          </a-col>
          <a-col :span="2">
            <div class="imglist">
              <a-space :size="4">
                <a-avatar-group :size="36">
                  <a-avatar :style="{ backgroundColor: '#7BC616' }">
                    <img alt="avatar" src="/img/xuexi.png" />
                  </a-avatar>
                </a-avatar-group>
              </a-space>
            </div>
          </a-col>
          <a-col :span="4">
            <div class="RealName">
              <a-button class="buttons" @click="handleClick">{{
                myObject.RealName
              }}</a-button>
            </div>
          </a-col>
        </a-row>
      </a-space>

      <!-- <div>
        11
    </div> -->
    </div>
  </div>
  <transition name="collapse">
    <div class="peilian" v-if="sparringlist">
      <!-- 这里放置陪练列表的具体内容 -->
      <Accompany @updateVisibility="updateVisibility" />
    </div>
  </transition>

  <a-drawer :width="240" :visible="visible" @cancel="handleCancel" :mask-closable="true" unmountOnClose :footer="false">
    <template #title> <icon-settings />&nbsp; &nbsp; 个人中心 </template>
    <div>
      <!-- <a-button class="anbutton" @click="goToH5">
        <icon-share-alt /> &nbsp; &nbsp;每日报告</a-button> -->
      <a-button class="anbutton" @click="handleCancel">
        <icon-align-right />
        <RouterLink to="/MyPractise" style="color: inherit;"> &nbsp; &nbsp;我的练习</RouterLink>
      </a-button>
      <a-button class="anbutton" @click="changePwd">
        <icon-lock />&nbsp; &nbsp;修改密码</a-button>
      <a-popconfirm content="您确定要退出吗?" @ok="logout" position="lt">
        <a-button class="anbutton"><icon-import /> &nbsp; &nbsp;退出登陆</a-button>
      </a-popconfirm>
    </div>
  </a-drawer>

  <a-modal title="修改密码" :visible="visiblePwd" @ok="handleOkPwd" @cancel="handleCancelPwd">
    <a-form :model="form" ref="formRef">
      <a-form-item field="oldPassword" label="旧密码" name="oldPassword">
        <a-input-password :max-length=25 :min-length=6 v-model="form.oldPassword" placeholder="请输入旧密码" />
      </a-form-item>
      <a-form-item field="newPassword" label="新密码" name="newPassword">
        <a-input-password :max-length=25 :min-length=6 v-model="form.newPassword" placeholder="请输入新密码" />
      </a-form-item>
      <a-form-item field="confirmPassword" label="确认新密码" name="confirmPassword">
        <a-input-password :max-length=25 :min-length=6 v-model="form.confirmPassword" placeholder="请再次输入新密码" />
      </a-form-item>
    </a-form>
  </a-modal>

</template>
<script lang="ts" setup>
import { Message } from "@arco-design/web-vue";
import { ref, reactive, onMounted, onUnmounted, watch, defineEmits, defineProps } from "vue";
import type { CSSProperties } from 'vue';
import { useRouter, useRoute } from "vue-router";
import Accompany from "./peilian/lianxi.vue";
import useUserStore from "@/store/modules/user";
import { loginOutlogOut, changePassword } from "@/api/user";

const menuMedia = ref(false);
const emit = defineEmits(['update:message', 'update:menuMedia'])
const windowWidth = ref(window.innerWidth)
const userStore = useUserStore();
const sparringlist = ref(false);
const router = useRouter();
const route = useRoute();
let myObject = reactive<any>({});
const formdata = reactive({
  subjectId: "",
});

const props = defineProps({
  showMenu: {
    type: Boolean,
    default: false,
  },
});


// 菜单数据与状态（横向显示）
const currentIndex = ref<number | null>(null);
const menuItems = [
  { index: 1, text: "首页", icon: "/img/shouye1.png", imgs: "/img/shouye2.png", url: "/home" },
  { index: 2, text: "AI精准测", icon: "/img/ce-1.png", imgs: "/img/ce-2.png", url: "/Measure" },
  { index: 3, text: "AI精准评", icon: "/img/zhen1.png", imgs: "/img/zhen2.png", url: "/Diagnosis" },
  { index: 4, text: "AI精准学", icon: "/img/xue1.png ", imgs: "/img/xue2.png", url: "/Study" },
  { index: 5, text: "AI精准练", icon: "/img/lian1.png", imgs: "/img/lian2.png", url: "/Practise" },
  // { index: 6, text: "考", icon: "/img/kao1.png", imgs: "/img/kao2.png", url: "/Examination" },
  // { index: 7, text: "陪", icon: "/img/pei1.png", imgs: "/img/pei2.png", url: "/Accompany" },
];

const clickmenuItem = (index: number, url: string) => {
  localStorage.setItem("index", String(index));
  currentIndex.value = index;
  router.push(url);
};

// 读取 logo，与 sider 保持一致
const logoUrl = ref<string | undefined>();
logoUrl.value = "/img/denglu.png";
// 定义拖动相关的响应式数据
const draggableBtn = ref(null);
const isDragging = ref(false);
const startX = ref(0);
const startY = ref(0);
const startLeft = ref(0);
const startTop = ref(0);
const currentLeft = ref(0);
const currentTop = ref(0);
const touchClickTimer = ref<ReturnType<typeof setTimeout> | null>(null); // 用于处理触摸点击的定时器
const isClick = ref(true);
// 定义盒子的样式（包括初始位置等）
const buttonStyle = ref<CSSProperties>({
  position: "fixed",
  right: "1%",
  top: "30%",
  cursor: "move",
  zIndex: 1000,
  left: "auto",
  transition: "none",
});

const handleChangeMenu = () => {
  menuMedia.value = !menuMedia.value;
  emit('update:menuMedia', menuMedia.value)
}

// 点击事件处理函数（原有的功能）
const sparring = () => {
  // 这里可以添加你原来的点击逻辑
  sparringlist.value = !sparringlist.value;
};

// 开始拖动事件处理函数
const startDrag = (e) => {
  isDragging.value = true;
  isClick.value = true;
  if (e.type === "touchstart") {
    touchClickTimer.value = setTimeout(() => {
      isClick.value = false;
    }, 300);
  }

  // 获取初始位置
  if (e.type === "mousedown") {
    startX.value = e.clientX;
    startY.value = e.clientY;
  } else if (e.type === "touchstart") {
    startX.value = e.touches[0].clientX;
    startY.value = e.touches[0].clientY;
  }

  // 获取当前按钮位置
  const rect = draggableBtn.value.getBoundingClientRect();
  startLeft.value = rect.left;
  startTop.value = rect.top;

  // 阻止默认行为和冒泡
  e.preventDefault();
  e.stopPropagation();
};

// 拖动中事件处理函数
const onDrag = (e) => {
  if (!isDragging.value) return;
  isClick.value = false;
  let clientX, clientY;
  if (e.type === "mousemove") {
    clientX = e.clientX;
    clientY = e.clientY;
  } else if (e.type === "touchmove") {
    clientX = e.touches[0].clientX;
    clientY = e.touches[0].clientY;
  }

  // 计算新位置
  const dx = clientX - startX.value;
  const dy = clientY - startY.value;

  currentLeft.value = startLeft.value + dx;
  currentTop.value = startTop.value + dy;

  // 更新按钮位置
  buttonStyle.value.left = `${currentLeft.value}px`;
  buttonStyle.value.top = `${currentTop.value}px`;

  e.preventDefault();
};

// 结束拖动事件处理函数
const endDrag = (e) => {
  if (!isDragging.value) return;
  isDragging.value = false;

  // 自动靠右
  const windowWidth = window.innerWidth;
  const buttonWidth = draggableBtn.value.offsetWidth;

  // 计算靠右位置（留 10px 边距）
  const rightPosition = windowWidth - buttonWidth - 10;

  // 平滑过渡到右侧
  buttonStyle.value.transition = "left 0.3s ease";
  buttonStyle.value.left = `${rightPosition}px`;

  // 过渡结束后移除 transition 属性，避免影响下次拖动
  setTimeout(() => {
    buttonStyle.value.transition = "none";
  }, 300);

  if (e.type === "mouseup") {
    if (isClick.value) {
      sparring();
    }
  } else if (e.type === "touchend") {
    clearTimeout(touchClickTimer.value);
    if (isClick.value) {
      sparring();
    }
  }
};
const h5SubjectID = ref();
const h5SuserId = ref();
// 查询按钮
const searchButtonClick = (e: any) => {
  userStore.setSubjectID(e);
  // h5SubjectID.value = e
  // localStorage.setItem('subjectID',e)
  // searchForm.pageNum = 1;
  // getPageData();
};
//h5
const goToH5 = () => {
  // 普通跳转
  // router.push("/H5Layout");
  // const userId = localStorage.getItem(permission)
  // 或者带参数跳转
  // router.push({
  //   path: "/H5Layout",
  //   query: {
  //     subjectID: h5SubjectID.value,
  //     userId: h5SuserId.value,
  //   },
  // });

  // 或者替换当前路由（无历史记录）
  // 构建带有查询参数的 URL
  const queryParams = new URLSearchParams({
    subjectID: h5SubjectID.value,
    userId: h5SuserId.value
  }).toString();
  const url = `/H5Layout?${queryParams}`;

  // 打开新窗口进行跳转
  window.open(url, '_blank');
  // router.replace('/h5/home')
};

watch(
  () => userStore.$state.subjectID,
  async (newValue, oldValue) => {
    try {
      // RefundReadForm.subjectID = userStore.$state.subjectID;
      h5SubjectID.value = userStore.$state.subjectID;
      // if (userStore.$state.subjectID) {
      // }
      // console.log(oldValue,'??')
      // console.log(newValue,'新值')
      // const storedPermission = JSON.parse(localStorage.getItem("permission"));
      // if(storedPermission){
      //   if (storedPermission.subjectIds.length > 0) {
      //     newValue = storedPermission.subjectIds[0];
      //   }
      // }
      formdata.subjectId = newValue;
      // docsaveData.value = data;
    } catch (error) {
      console.error("获取数据出错:", error);
    }
  },
  { immediate: true }
);

watch(
  () => props.showMenu,
  (newVal, oldVal) => {
    menuMedia.value = newVal;
  }
);

const indexValue = ref(localStorage.getItem("index"));
const handleLocalStorageChange = () => {
  const newValue = localStorage.getItem("index");
  if (indexValue.value !== newValue) {
    indexValue.value = newValue;
  }
};

// const sparring = () => {
//   sparringlist.value = !sparringlist.value;
// };
// 自定义事件处理函数
const updateVisibility = (newValue: any) => {
  sparringlist.value = newValue;
};
//抽屉
const visible = ref(false);
const visiblePwd = ref(false);
const form = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});
const formRef = ref(null);
const showModal = () => {
  visiblePwd.value = true;
};
const handleOkPwd = async () => {
  if (form.oldPassword == '' || form.newPassword == '' || form.confirmPassword == '') {
    Message.error('不能为空');
    return false;
  }
  // 验证新密码输入一致
  if (form.newPassword != form.confirmPassword) {
    Message.error('两次输入的密码不一致');
    return false;
  }
  if (form.oldPassword == form.newPassword) {
    Message.error('新密码不能和旧密码相同');
    return false;
  }
  const userInfo = JSON.parse(localStorage.getItem("permission"));
  const param = {
    'username': userInfo['UserName'],
    'newPassword': form.newPassword,
    'oldPassword': form.oldPassword
  }
  changePassword(param).then((res: any) => {
    localStorage.clear(); // 清除缓存s
    if (userInfo.suffix == '') {
      router.push("/");
    } else {
      router.push({
        name: 'login',
        query: { code: userInfo.suffix }
      });
      // router.push("/login?code=" + logoutUserInfo.suffix);
    }
  });
};
const handleCancelPwd = () => {
  formRef.value.resetFields();
  visiblePwd.value = false;
};

const handleClick = () => {
  visible.value = true;
};

const handleOk = () => {
  visible.value = false;
};
const handleCancel = () => {
  visible.value = false;
};

onMounted(() => {
  if (windowWidth.value < 768) {
    menuMedia.value = false;
  } else {
    menuMedia.value = true;
  }
  // 初始化当前路由对应的菜单高亮
  const targetItem = menuItems.find(item => item.url === route.path);
  if (targetItem) {
    currentIndex.value = targetItem.index;
  }
  window.addEventListener("localStorageChanged", handleLocalStorageChange);
  // myObject = JSON.parse(localStorage.getItem("permission") as any);
  window.addEventListener("mousemove", onDrag);
  window.addEventListener("touchmove", onDrag, { passive: false });
  window.addEventListener("mouseup", endDrag);
  window.addEventListener("touchend", endDrag);
  const permissionData = JSON.parse(localStorage.getItem("permission") as any);
  if (permissionData) {
    h5SuserId.value = permissionData.UserID;
    try {
      Object.keys(permissionData).forEach((key) => {
        myObject[key] = permissionData[key];
      });
    } catch (error) {
      // message.error('解析 localStorage 数据失败');/SubjectID
    }
  }




});

// 路由变化时更新菜单高亮
watch(
  () => route.path,
  (newPath) => {
    const targetItem = menuItems.find(item => item.url === newPath);
    if (targetItem) {
      currentIndex.value = targetItem.index;
    }
  }
);
const logout = () => {

  loginOutlogOut().then((res: any) => {
    const logoutUserInfo = JSON.parse(localStorage.getItem("permission"));
    // logoUrl.value = JSON.parse(localStorage.getItem("permission"))?.url;
    localStorage.clear(); // 清除缓存s
    if (logoutUserInfo.suffix == '') {
      router.push("/");
    } else {
      router.push({
        name: 'login'
      });
      // router.push("/login?code=" + logoutUserInfo.suffix);
    }
  });
};
const changePwd = () => {
  showModal();
};


onUnmounted(() => {
  window.removeEventListener("mousemove", onDrag);
  window.removeEventListener("touchmove", onDrag);
  window.removeEventListener("mouseup", endDrag);
  window.removeEventListener("touchend", endDrag);
  if (touchClickTimer.value) {
    clearTimeout(touchClickTimer.value);
    touchClickTimer.value = null;
  }
  window.removeEventListener("localStorageChanged", handleLocalStorageChange);
});
</script>
<style lang="less" scoped>
.buttons {
  background-color: #fff;
}

.header {
  margin: 0 100px;
  display: flex;
  font-size: 16px;
  justify-content: space-between;
}

.anbutton {
  width: 100%;
  margin-top: 1vw;
}

.rigrt {
  // width: 600px;
  margin-right: 10px;
  // background-color: pink;
}

.imglist {
  display: grid;
  place-items: center;
  height: 60px;
}

.imgwuxiaoxi {
  width: 1.5vw;
  height: 2vh;
  margin: 0 5px;
}

.RealName {
  // margin-left: ;
  cursor: pointer;
}

.fuchuang {
  width: 3vw;
  height: 6vh;
  cursor: pointer;
  z-index: 888;
  right: 15px !important;
  top:280px !important;
}

.fuchuang-img {
  width: 100%;
  height: 100%;
  user-select: none;
  /* 防止拖动时选中文本 */
  touch-action: none;
  /* 禁用触摸默认行为 */
}

.peilian {
  position: fixed;
  width: 40vw;
  right: 60px;
  top: 280px;
  border-radius: 12px;
  // background-color: pink;
  z-index: 77;
  box-shadow: 0px 0px 10px #ccc;
}

// 横向菜单样式（靠左排列）
.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-logo {
  width: 100px;
}

.header-menu {
  display: flex;
  align-items: center;
  gap: 12px;
}

.menu-item,
.menu-item-active {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 0px 10px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 700;
  color: #03305c;
  background: #F8FBFF;
}

.menu-item-active {
  background: #0075ff;
  color: #fff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2), inset 0 -2px 4px rgba(255, 255, 255, 0.4);
}

.menu-icon {
  width: 18px;
  height: 18px;
}

@media (max-width: 735px) {
  .header {
    margin: 0 0px;
    display: flex;
    // height:30px;
    font-size: 1.8vw;
    justify-content: space-between;
  }

  .xueke {
    font-size: 3vw;
  }

  .kuandu {
    width: 88px;
    font-size: 14px;
    // background-color: pink;
  }

  .fuchuang {
    position: absolute;
    width: 11vw;
    height: 6vh;
    cursor: pointer;
    // background-color: pink;
    right: 1%;
    bottom: 50%;
    z-index: 888;
  }

  .peilian {
    position: fixed;
    width: 60vw;
    height: 50vh;
    right: 40px;
    bottom: 40%;
    border-radius: 12px;
    // background-color: pink;
    z-index: 77;
  }

  .rigrt {
    // width: 200px;
    // background-color: pink;
  }

  .selectname {
    width: 2vw;
  }

  .imglist {
    display: grid;
    place-items: center;
    height: 60px;

    // width: 20px;
    // height: 20px;
    // background-color: pink;
  }

  .imgwuxiaoxi {
    width: 3vw;
    height: 2vh;
    margin-left: 5px;
  }
}

@media (max-width: 768px) {
  .grid-demo {
    line-height: 60px !important;
  }
}
</style>
